var AjaxForm = function () {
	
	var formvalidata = function (formId, module, method, rules, obj, sort) {

            var form = $('#' + formId);
            var error = $('.alert-error', form);
			
            form.validate({
                errorElement: 'span', //default input error message container
                errorClass: 'help-inline', // default input error message class
                focusInvalid: false, // do not focus the last invalid input
                ignore: "",
                rules: rules,
				
                invalidHandler: function (event, validator) { //display error alert on form submit 
                    error.show();
                },

                highlight: function (element) { // hightlight error inputs
                    $(element)
                        .closest('.help-inline').removeClass('ok'); // display OK icon
                    $(element)
                        .closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
                },

                unhighlight: function (element) { // revert the change dony by hightlight
                    $(element)
                        .closest('.control-group').removeClass('error'); // set error class to the control group
                },

                success: function (label) {
                    label
                        .addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
                    .closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
                },

                submitHandler: function (form) {
                    conductAction(module, method, formId, obj, sort);
                }
    	});
  	};
  	
  	//生成表单
	var createTable = function(obj, tabledata, sort){
		var tableHtml = '<table class="table table-striped table-bordered table-hover" id="datatable">';
		if(tabledata.caption !== 'undefined'){//表标题
			tableHtml += '<caption style="font-size:24px; margin-bottom: 10px;">' + tabledata.caption.captionhead +'</caption><caption style="font-size:18px; margin-bottom: 10px;">起始日期：' + tabledata.caption.timestart + '&nbsp;&nbsp;&nbsp;结束日期：' + tabledata.caption.timeend + '</caption>';
		}
		tableHtml += '</table>';
		$(obj).html(tableHtml);
		var columns = tabledata.columns;
		var aoColumns = new Array();
        var aaSorting = new Array();
		if(!(sort == null || sort === "undefined")){
        	for(var i = 0; i < columns.length; i++){
        		aoColumns.push({"bSortable": false, "sTitle": columns[i]});
        	}
        	for(var i = 0; i < sort[1].length; i++){
        		aoColumns[sort[1][i]].bSortable = true;
        	}
        	aaSorting.push(new Array(sort[0], 'desc'));
        }else{
        	aaSorting.push(new Array(0, 'desc'));
        }
		$('#datatable').dataTable({
			"aaData": tabledata.data,
			"aoColumns": aoColumns,
            "aaSorting": aaSorting,
            "oLanguage": {
            	"sLengthMenu": "每页显示 _MENU_ 条记录",
				"sZeroRecords": "抱歉， 没有找到相应记录",
				"sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
				"sInfoEmpty": "没有数据",
				"sInfoFiltered": "(从 _MAX_ 条数据中检索)",
				"oPaginate": {
					"sFirst": "首页",
					"sPrevious": "前一页",
					"sNext": "后一页",
					"sLast": "尾页"
				},
            	"sSearch": "搜索:"
            },
            "sZeroRecords": "没有检索到数据",
            // set the initial value
            "iDisplayLength": 10,
            "sDom": "<'row-fluid'<'span3'T><'span4'f><'span5'p>r>t<'row-fluid'<'span6'i>>",
			"oTableTools": {
				"sSwfPath": "../Public/swf/copy_csv_xls_pdf.swf",
				"aButtons": [
					{
						"sExtends":    "copy",
						"sButtonClass": "black",
						"sButtonText": '<i class="icon-copy"></i>&nbsp;&nbsp;复制   '
					},
					{
						"sExtends":    "print",
						"sButtonClass": "black print",
						"bShowAll": true,
						"sButtonText": '<i class="icon-print"></i>&nbsp;&nbsp;打印  '
					},
					{
						"sExtends":    "collection",
						"sButtonClass": "black",
						"sButtonText": '<i class="icon-save"></i>&nbsp;&nbsp;保存为    <span class="caret" />',
						"aButtons":    [ 
							{
								"sExtends":    "csv",
								"sButtonText": '&nbsp;&nbsp;CSV文件',
								"sFileName": tabledata.caption.captionhead + " - 皇家鸡排.csv",
								"sTitle": ""
							},
							{
								"sExtends":    "xls",
								"sButtonText": '&nbsp;&nbsp;Excel文件',
								"sFileName": tabledata.caption.captionhead + " - 皇家鸡排.xls",
								"sTitle": ""
							},
							{
								"sExtends":    "pdf",
								"sButtonText": '&nbsp;&nbsp;PDF文件',
								"sFileName": tabledata.caption.captionhead + " - 皇家鸡排.pdf",
								"sTitle": ""
							}]
					}
				]
			}
		});
	};
    
    var conductAction = function(module, method, formId, obj, sort){
    		App.blockUI($(obj).parent().parent().parent().parent());
 			this.actionModule = module;
			//this.method = method;
			this.data = $('#' + formId).serialize();
			
			this.url = hjjp_rootUrl + "/" + this.actionModule + "/" + method + "json";
			$.post(this.url, this.data, function(resp){
				if(resp.status === 200){
					if($("#datatable").length > 0){
						$("#datatable").remove();
					}
					createTable(obj, resp.tabledata, sort);
					$('a.print').unbind();
					$('a.print').click(function(){
						$('#datatable').jqprint({ operaSupport: true });
					});
					window.setTimeout(function () {
	                    App.unblockUI($(obj).parent().parent().parent().parent());
	                }, 500);
					if($(obj).hasClass("hide")){
						$(obj).removeClass("hide");
					}
				}else{
					$.scojs_message(resp.errorMsg, $.scojs_message.TYPE_ERROR);
				}
			}, "json");
 	};

    return {
        //main function to initiate the module
        init: function (formId, module, method, rules, obj, sort) {
            formvalidata(formId, module, method, rules, obj, sort);//初始化表单验证
        }

    };

}();